package ssm.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import ssm.pojo.Pager;
import ssm.pojo.User;
import ssm.service.IUserService;

import javax.annotation.Resource;

/**
 * herochen
 * Date: 17-5-26
 */
@Controller

public class UserController {

    @Resource
    private IUserService userService;

    @RequestMapping(value = "/user/add",method = RequestMethod.GET)//到addUser.jsp页面的方法
    public String getAddUserPage(){
        return "addUser";
    }
//添加用户
    @RequestMapping(value = "/user",method = RequestMethod.POST)
    public String addUser(User user){
        System.out.println(user);
        userService.addUser(user);
        return "redirect:/users";
    }

    //展示用户
    @RequestMapping(value = "/users",method = RequestMethod.GET)
    public String showUsers(){


        return "redirect:/users/1";
    }

    @RequestMapping(value = "/users/{pageIndex}",method = RequestMethod.GET)

    public String users(Model model,@PathVariable int pageIndex){
        Pager pager=userService.findUserByPageIndex(pageIndex);
        model.addAttribute("pager",pager);

        return "users";
    }


    //根据ID删除一个用户
    @RequestMapping(value = "/user/delete/{id}",method = RequestMethod.GET)
    public String deleteUserById(@PathVariable int id){
        userService.deleteUserById(id);
        return "redirect:/users";
    }

    //编辑一个用户
    @RequestMapping(value = "/user/edit/{id}",method =RequestMethod.GET )
    public String editUserById(@PathVariable int id,Model model){
        User user=userService.findById(id);
        model.addAttribute("user", user);
        return "editUser";
    }
    //更新用户显示
    @RequestMapping(value = "/user/update/{id}",method =RequestMethod.POST )
    public String updateUserById(@PathVariable int id,User user){
        user.setUserId(id);
        userService.updateUserById(user);
        return "redirect:/users";
    }

    //注册
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String getLoginPage(){
        return "login";
    }

   @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(String username,String password,Model model){
    if(password.equals(userService.findPasswordByUsername(username))){
        return "redirect:/users";
    }else {
        model.addAttribute("message","您的密码或账号不正确");
        return "/login";
    }

   }


}
